#!/bin/bash

# Java 17问题修复脚本
echo "🔧 Java 17问题修复工具"
echo "======================"

# 检查当前Java版本
echo "📊 当前Java版本:"
java -version 2>&1 | head -n 3

echo ""
echo "🔍 检查Java 17安装状态..."

# 查找Java 17路径
JAVA_17_PATH="/Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home"

if [ -d "$JAVA_17_PATH" ]; then
    echo "✅ Java 17已安装: $JAVA_17_PATH"
else
    echo "❌ Java 17未找到"
    echo "📦 开始安装Java 17..."
    
    # 提供安装选项
    echo "请选择安装方式:"
    echo "1) 使用Homebrew安装 (推荐)"
    echo "2) 从Oracle官网下载"
    echo "3) 使用SDKMAN安装"
    
    read -p "选择 (1-3): " choice
    
    case $choice in
        1)
            echo "📦 使用Homebrew安装..."
            brew install openjdk@17
            sudo ln -sfn /opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/jdk-17.jdk
            ;;
        2)
            echo "🌐 请访问: https://www.oracle.com/java/technologies/downloads/#java17"
            echo "下载并安装Java 17 for macOS"
            exit 1
            ;;
        3)
            echo "📦 安装SDKMAN..."
            curl -s "https://get.sdkman.io" | bash
            source ~/.sdkman/bin/sdkman-init.sh
            sdk install java 17.0.8-tem
            ;;
        *)
            echo "❌ 无效选择"
            exit 1
            ;;
    esac
fi

# 设置环境变量
echo "⚙️  配置环境变量..."
export JAVA_HOME=$JAVA_17_PATH
export PATH=$JAVA_HOME/bin:$PATH

# 验证配置
echo "✅ 环境变量设置完成"
echo "JAVA_HOME=$JAVA_HOME"

# 添加到shell配置
echo "💾 添加到shell配置文件..."
SHELL_RC=""
if [ -f ~/.zshrc ]; then
    SHELL_RC=~/.zshrc
elif [ -f ~/.bashrc ]; then
    SHELL_RC=~/.bashrc
fi

if [ -n "$SHELL_RC" ]; then
    # 移除旧的JAVA_HOME配置
    sed -i '' '/JAVA_HOME/d' "$SHELL_RC" 2>/dev/null || true
    
    # 添加新的配置
    echo "" >> "$SHELL_RC"
    echo "# Java 17配置" >> "$SHELL_RC"
    echo "export JAVA_HOME=$JAVA_17_PATH" >> "$SHELL_RC"
    echo 'export PATH="$JAVA_HOME/bin:$PATH"' >> "$SHELL_RC"
    echo "✅ 已添加到 $SHELL_RC"
fi

# 验证Maven配置
echo "🔍 验证Maven配置..."
if command -v mvn &> /dev/null; then
    echo "✅ Maven已配置:"
    mvn -version | grep "Java version"
else
    echo "❌ Maven未安装"
    echo "📦 安装Maven: brew install maven"
fi

# 测试编译
echo "🧪 测试项目编译..."
cd "$(dirname "$0")"
if mvn clean compile -DskipTests -q 2>/dev/null; then
    echo "✅ 项目编译成功"
else
    echo "⚠️  项目编译可能有错误，请检查日志"
fi

echo ""
echo "🎉 Java 17配置完成！"
echo "💡 提示: 重新打开终端或运行 'source ~/.zshrc' 使配置生效"
echo "🚀 现在可以运行: ./start-with-existing-db.sh 启动项目"